public class Main {
    /*
     * 填充每一个节点的下一个右侧节点指针II
     *
     * */
    public aNode connect21(aNode root) {
        if (root == null) {
            return root;
        }
        Queue<aNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            aNode pre = queue.peek();
            while (size > 0) {
                aNode node = queue.poll();
                if (pre != node) {
                    pre.next = node;
                    pre = node;
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
        }
        return root;
    }

    /*
     * 出大事了，传参 和 传值 一定要明确
     *
     * */
    aNode pre = null;
    aNode head = null;

    public void handle(aNode p) {
        if (pre == null) {
            pre = p;
        } else {
            pre.next = p;
            pre = p;
        }
        if (head == null) {
            head = p;
        }
    }

    public aNode connect23(aNode root) {
        aNode cur = root;
        while (true) {
            head = null;
            pre = null;
            while (cur != null) {
                if (cur.left != null) {
                    handle(cur.left);
                }
                if (cur.right != null) {
                    handle(cur.right);
                }
                cur = cur.next;
            }
            if (head == null) {
                return root;
            }
            cur = head;
        }
    }

    /*
     * 此处是传值调用，并非传址调用
     *
     * */
    public void handle(aNode p, aNode pre, aNode head) {
        if (pre == null) {
            pre = p;
        } else {
            pre.next = p;
            pre = p;
        }
        if (head == null) {
            head = p;
        }
    }

    public aNode connect24(aNode root) {
        aNode cur = root;
        while (true) {
            head = null;
            pre = null;
            while (cur != null) {
                if (cur.left != null) {
                    handle(cur.left, pre, head);
                }
                if (cur.right != null) {
                    handle(cur.right, pre, head);
                }
                cur = cur.next;
            }
            if (head == null) {
                return root;
            }
            cur = head;
        }
    }
}